@extends('layouts.app')
@section('title', $product->title)

@section('content')
    <div class="row">
        <div class="col-lg-10 offset-lg-1">
            <div class="card">
                <div class="card-body product-info">
                    <div class="row">
                        <div class="col-5">
                            <img class="cover" src="{{ $product->image_url }}" alt="">
                        </div>
                        <div class="col-7">
                            <div class="title">{{ $product->title }}</div>
                            <div class="crowdfunding-info">
                                <div class="have-text" style="color: red;">
                                    竞拍时间: {{ \Illuminate\Support\Carbon::parse($product->start_at)->format('Y-m-d H:i:s') }}
                                    ~ {{ \Illuminate\Support\Carbon::parse($product->end_at)->format('Y-m-d H:i:s') }}</div>
                                <div class="total-amount"><span class="symbol">底价￥ {{ $product->price }}</span></div>

                                <div class="progress-info">
                                    <span id="end-time" style="color: blue; font-size: 16px;"></span>
                                    <span class="float-right user-count">{{ $product->participate_count ?? 0 }} 名参与者</span>
                                </div>
                            </div>
                            <div class="price"><label>当前价格</label><em>￥</em><span>{{ $product->biddingList->isEmpty() ? $product->price : $product->biddingList->max('now_price')}}</span></div>
                            <div class="buttons">
                                @if(Auth::check())
                                    <button type="button" class="btn btn-primary btn-modal-bidding">参与拍卖</button>
                                @else
                                    <a class="btn btn-primary" href="{{ route('login') }}">请先登录</a>
                                @endif
                            </div>
                        </div>

                        <div class="col-12">
                            <h3 style="margin:20px 0 5px 0; color: red;">火热竞拍中</h3>
                        </div>
                        <div class="col-12">
                            <!-- 实时竞拍信息推送框start -->
                            <div class="lite-chatbox">
                                <!-- cleft 左 -->
                                @if(isset($product->biddingList) && Auth()->check())
                                    @foreach($product->biddingList as $value)
                                        @if($value->user_id == Auth()->user()->id)
                                            <div class="cleft cmsg">
                                                <img class="headIcon radius" ondragstart="return false;" oncontextmenu="return false;" src="{{ asset('assets/images/robot.png') }}"/>
                                                <span class="name">{{ $value->created_at }}</span>
                                                <span class="content"><span style="color: orangered; font-size: 16px; font-weight: bold">您 </span>加价{{ $value->money }}元. 商品目前价格为{{ $value->now_price }}元 @if ($loop->last)<span style="color: red; font-weight: bold">&nbsp;&nbsp;最新 </span> @endif</span>
                                            </div>
                                        @else
                                            <div class="cright cmsg">
                                                <img class="headIcon radius" ondragstart="return false;"
                                                     oncontextmenu="return false;" src="{{ asset('assets/images/robot.png') }}"/>
                                                <span class="name">{{ $value->created_at }}</span>
                                                <span class="content"><span style="color: orangered; font-size: 16px; font-weight: bold">{{ $value->user->is_admin || !$value->user->is_show ? "匿名用户 " : $value->user->name }}</span>加价{{ $value->money }}元. 商品目前价格为{{ $value->now_price }}元 @if ($loop->last)
                                                        <span class="bidding-last-message" style="color: red; font-weight: bold"> 最新 </span> @endif</span>
                                            </div>
                                        @endif
                                    @endforeach
                                @else
                                    <div class="cright cmsg">
                                        <img class="headIcon radius" ondragstart="return false;"
                                             oncontextmenu="return false;" src="{{ asset('assets/images/robot.png') }}"/>
                                        <span class="name">小小机器人</span>
                                        <span class="content">登录即可查看竞价信息 <a href="{{route('login')}}">点我登录~</a></span>
                                    </div>
                                @endif
                            </div>
                            <!-- 实时竞拍信息推送框end -->
                        </div>
                    </div>
                    <div class="product-detail">
                        <ul class="nav nav-tabs" role="tablist">
                            <li class="nav-item">
                                <a class="nav-link active" href="#product-detail-tab" aria-controls="product-detail-tab"
                                   role="tab" data-toggle="tab" aria-selected="true">商品详情</a>
                            </li>
                        </ul>
                    </div>

                    <div class="tab-content">
                        <div role="tabpanel" class="tab-pane active" id="product-detail-tab">
                            <!-- 产品属性开始 -->
                            <div role="tabpanel" class="tab-pane active" id="product-detail-tab">
                                {!! $product->description !!}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 竞价弹框开始 -->
    <div class="modal" id="bidding-modal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
                    <table class="table table-bordered table-striped text-center" style="width: 600px">
                        <thead>
                        <tr>
                            <th class="text-center">加价方案</th>
                            <th class="text-center">加价金额</th>
                            <th></th>
                        </tr>
                        </thead>
                        <tbody>
                        @for($i = 1; $i < 6; $i ++)
                            <tr>
                                <td>方案{{ $i }}</td>
                                <td>{{ $i * $product->minimum_markup }}¥</td>
                                <td>
                                    <button class="btn btn-sm btn-primary btn-bidding"
                                            data-money="{{ $i * $product->minimum_markup }}">选择
                                    </button>
                                </td>
                            </tr>
                        @endfor
                        <tr>
                            <td>自定义方案</td>
                            <td>
                                <div class="input-group mb-3">
                                    <input type="text" class="form-control" name="customizeMoney"
                                           placeholder="不得低于{{$product->minimum_markup}}¥"
                                           aria-label="Recipient's username" aria-describedby="basic-addon2">
                                    <div class="input-group-append">
                                        <span class="input-group-text" id="basic-addon2">¥</span>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-primary btn-bidding">选择</button>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                </div>
            </div>
        </div>
    </div>
    <!-- 竞价弹框结束 -->
@endsection

@section('scriptsAfterJs')
    <script>
        $(function () {
            // 开启倒计时
            countTime();

            @if(Auth()->check())
            // 定时获取竞价信息
            getBidding();
            @endif

            // 打开加价模态框
            $('.btn-modal-bidding').click(function () {
                let date = new Date()
                let now = date.getTime() //获取当前时间

                let endTime = "{{ \Illuminate\Support\Carbon::parse($product->end_at)->timestamp }}" //设置截止时间 ，后台传入考试结束时间即可
                endTime = parseInt(endTime)

                //js和php的时间戳相互转化要*1000
                let end = endTime * 1000
                //时间差
                let leftTime = end - now
                if (leftTime <= 0) {
                    swal('竞拍已结束', '', 'warning')
                }

                $('#bidding-modal').modal();
            });

            // 点击加价按钮
            $('.btn-bidding').click(function () {
                let money = typeof ($(this).data('money')) !== "undefined"
                    ? $(this).data('money')
                    : $("input[name=customizeMoney]").val().trim();

                if (money === "" || typeof (money) === "undefined") {
                    swal('请选择加价金额', '', 'error');
                    return;
                }

                money = parseFloat(money);  // 用户加价
                let minimum_markup = "{{ $product->minimum_markup }}";
                minimum_markup = parseFloat(minimum_markup);   // 最低加价金额

                if (money < minimum_markup) {
                    swal('自定金额小于最低加价金额', '', 'error');
                    return;
                }

                swal({
                    title: "是否确定加价" + money + "元?",
                    icon: "warning",
                    buttons: ['取消', '确定'],
                    dangerMode: true
                }).then(function (willSave) {
                    if (!willSave) return;
                    // 调用竞价接口
                    axios.post('{{ route('product.bidding', ['product' => $product->id]) }}', {
                        'money': money
                    }).then((res) => {
                        if (res.status === 200) {
                            swal('加价成功!', '', 'success').then(function () {
                                location.reload();
                            });
                        }
                    }, function (error) {
                        if (error.response && error.response.status === 401) {
                            swal('请先登录', '', 'error');
                        } else if (error.response && (error.response.data.msg || error.response.data.message)) {
                            swal(error.response.data.msg ? error.response.data.msg : error.response.data.message, '', 'error');
                        } else {
                            swal('系统错误', '', 'error');
                        }
                    });
                })
            });
        })


        // 商品倒计时
        function countTime(callback) {
            let date = new Date()
            let now = date.getTime() //获取当前时间

            let endTime = "{{ \Illuminate\Support\Carbon::parse($product->end_at)->timestamp }}" //设置截止时间 ，后台传入考试结束时间即可
            endTime = parseInt(endTime)

            //js和php的时间戳相互转化要*1000
            let end = endTime * 1000
            //时间差
            let leftTime = end - now
            //定义变量 d,h,m,s保存倒计时的时间
            let d, h, m, s
            if (leftTime >= 0) {
                d = Math.floor(leftTime / 1000 / 60 / 60 / 24)
                h = Math.floor(leftTime / 1000 / 60 / 60 % 24)
                m = Math.floor(leftTime / 1000 / 60 % 60)
                s = Math.floor(leftTime / 1000 % 60)
            } else {
                $("#end-time").text("竞拍已结束!")
                return;
            }
            //将倒计时赋值到div中
            $('#end-time').text("竞拍剩余时间: " + h + "时 " + m + "分 " + s + "秒")
            //递归每秒调用countTime方法，显示动态时间效果
            this.setTimeout(countTime, 1000)
        }

        // getBidding本功能只有在登录后才能开启
        @if(Auth()->check())
        function getBidding() {
            let date = new Date()
            let now = date.getTime()  //获取当前时间
            let endTime = "{{ \Illuminate\Support\Carbon::parse($product->end_at)->timestamp }}" //设置截止时间 ，后台传入考试结束时间即可
            endTime = parseInt(endTime)
            //js和php的时间戳相互转化要*1000
            let end = endTime * 1000
            let leftTime = end - now   //时间差
            if (leftTime < 0) {
                return; // 结束倒计时
            }
            axios.post("{{ route('product.get_bidding_list_by_bidding_id', ['product' => $product->id]) }}", {
                bidding_id: "{{ session('product.lastBiddingId') }}"
            }).then((res) => {
                let data = res.data.data;
                if (res.data.code !== 200 || data.length === 0) {
                    return;
                }
                $('.bidding-last-message').remove();

                let newMessage = '<span class="bidding-last-message" style="color: red; font-weight: bold">&nbsp;&nbsp;最新 </span>';

                let dom = '';
                for (let i = 0; i < data.length; i ++) {
                    let value = data[i];
                    let lastIndex = data.length - 1;
                    let position = value.user_id == "{{ Auth::user()->id }}" ? 'cleft' : 'cright';
                    let name = value.user_id == "{{ Auth::user()->id }}"  ? '您' : (value.user.is_admin || !value.user.is_show ? "匿名用户 " : value.user.name);

                    if (lastIndex === i) {
                        dom += '<div class="' + position + ' cmsg">'
                            + '<img class="headIcon radius" ondragstart="return false;"'
                            + 'oncontextmenu="return false;" src="{{ asset('assets/images/robot.png') }}"/>'
                            + '<span class="name">' + value.created_at + '</span>'
                            + '<span class="content"><span style="color: orangered; font-size: 16px; font-weight: bold"> ' + name + '</span> 加价' + value.money + '元. 商品目前价格为' + value.now_price + '元 ' + newMessage + '</span>'
                            + '</div>'
                    } else {
                        dom += '<div class="' + position + ' cmsg">'
                            + '<img class="headIcon radius" ondragstart="return false;"'
                            + 'oncontextmenu="return false;" src="{{ asset('assets/images/robot.png') }}"/>'
                            + '<span class="name">' + value.created_at + '</span>'
                            + '<span class="content"><span style="color: orangered; font-size: 16px; font-weight: bold">' + name + '</span> 加价' + value.money + '元. 商品目前价格为' + value.now_price + '元 '
                            + '</span>'
                            + '</div>'
                    }
                }
                $(".lite-chatbox").append(dom);
                $(".lite-chatbox").animate({
                    scrollTop: $(".lite-chatbox").get(0).scrollHeight
                });
            });

            this.setTimeout(getBidding, 10000); // 10秒获取一次数据
        }
        @endif
    </script>
@endsection
